import flash.events.Event;

import mx.controls.Alert;
import mx.events.SliderEvent;

import org.quantitativesustainability.dataStructures.AField;
import org.quantitativesustainability.events.EnableChangeEvent;

private var _aField:AField;

public function init(a:AField):void
{
    hslider.addEventListener(SliderEvent.CHANGE, handleHSlider);
    _aField=a;

    // Setup labels:
    var minSlider:Number=1e50;
    var maxSlider:Number=-1e50;
    for (var j:int=0; j < _aField.array.length; ++j)
    {
        if (_aField.array[j] < minSlider)
            minSlider=_aField.array[j]
        if (_aField.array[j] > maxSlider)
            maxSlider=_aField.array[j]
    }
    hslider.minimum=minSlider;
    hslider.maximum=maxSlider;
    var _labels:Array=[minSlider, maxSlider];
    hslider.labels=[minSlider, maxSlider];

    // Setup caption:
    caption.text=_aField.label;
    captionBox.move(hslider.x + hslider.width / 2.0, hslider.y - hslider.getStyle('labelOffset'));
}

private function handleHSlider(eventObj:Event):void
{
    // find nearest aField
    if (hslider.value >= hslider.maximum)
        _aField.index=_aField.array.length;
    else if (hslider.value <= hslider.minimum)
        _aField.index=0;
    else
    {
        var inc:int=1;
        if (hslider.value < _aField.array[_aField.index])
            inc=-1
        for (; _aField.index < _aField.array.length; _aField.index+=inc)
        {
            if (hslider.value >= _aField.array[_aField.index] && hslider.value <
                _aField.array[_aField.index + 1])
            {
                if (Math.abs(hslider.value - _aField.array[_aField.index]) > Math.
                    abs(hslider.value - _aField.array[_aField.index + 1]))
                    _aField.index+=1;
                break;
            }
        }
    }
    if (_aField.index >= _aField.array.length)
        Alert.show('sdfd');

    moveSlider();
}

public function moveSlider():void
{
    // Move hslider thumb;
    hslider.value=_aField.array[_aField.index];

    var eventObj:EnableChangeEvent=new EnableChangeEvent(EnableChangeEvent.ENABLE_CHANGED);
    eventObj.isEnabled=true;
    dispatchEvent(eventObj);

    // Move Label
    var y:Number=hsliderLabel.y;
    var x:Number=hslider.x + hslider.width * (hslider.value - hslider.minimum) /
        (hslider.maximum - hslider.minimum);
    hsliderLabel.move(x, y);
    hsliderLabel.htmlText='<i>' + String(_aField.array[_aField.index]) + '</i>';
}

public function set incAIndex(i:int):void
{
    _aField.index+=i;
    if (_aField.index < 0) _aField.index=0;
    if (_aField.index >= _aField.array.length) _aField.index=_aField.array.length-1;

    moveSlider();
}

